//
//  LoginViewModel.m
//  MVVM+RAC
//
//  Created by bopeng on 16/5/13.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "LoginViewModel.h"
#import "Account.h"
#import <SVProgressHUD/SVProgressHUD.h>



@implementation LoginViewModel

- (Account *)account {
    return _account ? : (_account = [[Account alloc] init]);
}

- (instancetype)init {
    if (self = [super init]) {
        [self initBind];
    }
    return self;
}

- (void)initBind {
    
    // 监听账号的属性值改变
    _enableLoginSignal = [RACSignal combineLatest:@[RACObserve(self.account, account),RACObserve(self.account, pwd)] reduce:^id(NSString *account, NSString *pwd){
        return @(account.length && pwd.length);
    }];
    
    _loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [subscriber sendNext:@"登录成功"];
                
                // 发送数据完毕
                [subscriber sendCompleted];
            });
            return nil;
        }];
    }];
    
    // 监听登录产生的数据
    [_loginCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        if ([x isEqualToString:@"登录成功"]) {
            // 这里进行跳转
            if (self.loginSubject) {
                [self.loginSubject sendNext:@"登录完成，进行跳转"];
                [self.loginSubject sendCompleted];
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:scottLoginSuccess object:nil];
        }
    }];
    
    // 监听登录状态
    [[_loginCommand.executing skip:1] subscribeNext:^(id x) {
        if ([x boolValue] == YES) { // 正在登录
            // 提示正在登录
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            [SVProgressHUD showWithStatus:@"正在登录..."];
        }else{  // 登录成功
            // 隐藏提示
            [SVProgressHUD dismiss];
        }
    }];
}

@end
